<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Member\Good;
use App\Models\Member\Grade;
use App\Models\Member\GoodPrice;
use App\Models\Member\User;
use App\Models\Member\Order;
use App\Models\Member\OrderItem;
use Auth;
use Config;
use Log;
use App\Models\Member\Address;
use App\Common\AliossHandler;

class OrderController extends Controller
{
    // 购物车结算 生成会员订单
    public function confirmOrder(Request $request)
    {
        $user = Auth::user()->toArray();
        $storeId = $user['store_id'];
        $data = $request->json('data');
        if (empty($data)) {
            return $this->errorClient($data, '提交数据为空');
        }
        $info = json_decode($data, true);
        $jf = 0;// 历史积分 - 决定了 是每次购买都重头开始计算 还是 看历史数据 , 目前只按照每次购买来算
        // 验证
        $check = $this->checkOrder($info, $user);
        if ($check['code'] != 20000) {
            return $check;
        }
        // 获取 上线的会员产品
        $goodsArray=array_keys($info);
        $Good = new Good;
        $goodsData = $Good->storeGoods($storeId, $goodsArray);
        $dataCart = $Good->foreachCart($info, $goodsData);
        $retailPrice = round($dataCart['retailPrice']/100, 2);
        $pointsAll = round($dataCart['pointsAll'], 2);
        $goodsNewArray = $dataCart['goodsNewArray'];
        // 获取价格阶梯 
        $Grade = new Grade;
        $grades = $Grade->storeGrade($storeId);// 获取 当前店铺的会员等级信息
        $gradesKeyVal = key_val($grades,'level');
        $GoodPrice = new GoodPrice;
        $priceArr = $GoodPrice->storeGoodsPrice($storeId, $goodsNewArray, $gradesKeyVal);
        // 获取预计达到的等级
        $jf = $jf + $retailPrice;
        $tips = $Grade->getTips($grades, $jf, $user);// 获取 底部提示文字
        // $level = $tips['priceGrade'];多等级价格取消 只保留会员价格
        $level = 0;
        Log::info('生成订单积分:'.$jf);
        Log::info('生成订单等级:'.$level);
        // 遍历合法商品数据 得出订单详情和其他数据
        $orderInfo = $this->setOrderInfo($retailPrice, $pointsAll);
        $OrderItem = new OrderItem;
        $orderItem = $OrderItem->setOrderItem($goodsData, $priceArr, $info, $level, $user, $orderInfo);
        
        return $orderItem;
    }

    // 会员订单使用或取消使用积分
    public function useJf(Request $request)
    {
        $user = Auth::user()->toArray();
        $orderId = $request['id'];
        $type = $request['type'];
        $Order = new Order;
        $orderInfo = [];
        $orderInfo['id'] = $orderId;
        if ($type == 1) {
            // 使用积分
            $OrderItem = new OrderItem;
            $jf = $OrderItem->getUseJf($orderId, $user);
            $orderInfo['jf_price'] = $jf;
            return $Order->updateMemOrder($orderInfo, 3);
        } else {
            // 不再使用积分
            $orderInfo['jf_price'] = 0;
            return $Order->updateMemOrder($orderInfo, 3);
        }
    }

    private function checkOrder($info, $user)
    {
        if (empty($info)) {
            return $this->errorClient($info, '购物车数据为空');
        }
        $Order = new Order;
        $notPay = $Order->getNotPayOrder($user['id']);// 获取指定状态的订单
        if (!empty($notPay)) {
            return $this->backJsonClient($notPay['id'], '存在未付款订单!', 20002);
        }
        return $this->successClient('', '验证成功!'); 
    }

    private function setOrderInfo($retailPrice, $pointsAll)
    {
        $orderInfo = [];
        $orderInfo['type'] = 1;
        $orderInfo['express_type'] = 'ZTO';
        $orderInfo['base_price'] = $retailPrice;
        $orderInfo['pay_price'] = 0;
        $orderInfo['jf'] = $pointsAll;
        return $orderInfo;
    }

    // 会员订单详情
    public function memOrderDetail(Request $request)
    {
        $orderId = $request['id'];
        if (empty($orderId)) {
            return $this->errorClient([], '参数不存在');
        }
        // $orderId = 5;
        $Order = new Order;
        $orederInfo = $Order->getOrder($orderId);
        if (empty($orederInfo)) {
            return $this->errorClient($orederInfo, '订单不存在');
        }
        $user = Auth::user()->toArray();
        if ($orederInfo['user_id'] != $user['id'] && $orederInfo['order_status'] == 2) {
            return $this->errorClient($orederInfo, '您无权查看此未付款订单');
        }
        $address_use = $orederInfo['order_status'] == 1 ? 0 : 1;// 是否显示地址
        if ($orederInfo['user_id'] != $user['id']) {
            $address_use = 0;// 非本人订单 不显示地址信息
        }
        $OrderItem = new OrderItem;
        $orederItemInfo = $OrderItem->getOrderItem($orderId);// 商品信息 - 商品主图 / 零售价 / 支付价 / 数目
        $tips = $Order->getMemOrderTips($orederInfo['order_status']);// 通过订单状态 获取 会员订单应当返还的tips
        
        foreach ($orederItemInfo as $key => $value) {
            $orederItemInfo[$key]['good_logo'] = AliossHandler::read('good', $value['good_logo']);
        }
        $data = [];
        $data['user'] = ['id' => $user['id'], 'phone' => $user['phone'], 'true_name' => $user['true_name'], 'nickname' => $user['nickname'], 'avatar' => $user['avatar']];
        $data['address_use'] = $address_use;
        $data['tips'] = $tips;
        $data['order'] = $orederInfo;
        $data['order_item'] = $orederItemInfo;
        $data['express_type'] = Config::get("const.express_type_str");
        $data['express_number'] = empty($orederInfo['express_number']) ? [] : explode(',', $orederInfo['express_number']);

        return $this->successClient($data, '订单详情获取成功!'); 
    }

    // 取消会员订单
    public function cancelMemOrder(Request $request)
    {
        $orderId = $request['id'];
        if (empty($orderId)) {
            return $this->errorClient([], '参数不存在');
        }
        // $orderId = 5;
        $Order = new Order;
        $orederInfo = $Order->getOrder($orderId);
        if (empty($orederInfo)) {
            return $this->errorClient($orederInfo, '订单不存在');
        }
        if ($orederInfo['order_status'] != 2) {
            return $this->errorClient($orederInfo['order_status'], '这不是待付款订单, 无法取消!');
        }
        $user = Auth::user()->toArray();
        if ($orederInfo['user_id'] != $user['id']) {
            return $this->errorClient($orederInfo['order_status'], '[会员订单取消]您无权取消此订单');
        }
        $cancel = $Order->cancelMemOrder($orderId);
        return $cancel;
    }

    // 会员订单收货
    public function accepterMemOrder(Request $request)
    {
        $orderId = $request['id'];
        if (empty($orderId)) {
            return $this->errorClient([], '参数不存在');
        }
        // $orderId = 5;
        $Order = new Order;
        $orederInfo = $Order->getOrder($orderId);
        if (empty($orederInfo)) {
            return $this->errorClient($orederInfo, '订单不存在');
        }
        if ($orederInfo['order_status'] != 4) {
            return $this->errorClient($orederInfo['order_status'], '这不是待收货订单, 无法收货!');
        }
        $user = Auth::user()->toArray();
        if ($orederInfo['user_id'] != $user['id']) {
            return $this->errorClient($orederInfo['order_status'], '[会员订单确认收货]您无权操作此订单');
        }
        $Order = new Order;
        $accepter = $Order->accepterMemOrder($orderId);
        return $accepter;
    }

    // 选择地址 事件 订单ID / 地址ID
    public function chooseAddress(Request $request)
    {
        if (empty($request)) {
            return $this->errorClient([], '参数不存在');
        }
        $orderId = $request['id'];
        $adId = $request['ad_id'];
        $user = Auth::user()->toArray();

        $Address = new Address;
        $addressInfo = $Address->getAddress($adId, $user['id']);

        $requestGet = [];
        $requestGet['id'] = $orderId;
        $requestGet['accepter_name'] = $addressInfo['accepter_name'];
        $requestGet['accepter_phone'] = $addressInfo['accepter_phone'];
        $requestGet['province_name'] = $addressInfo['province_name'];
        $requestGet['city_name'] = $addressInfo['city_name'];
        $requestGet['district_name'] = $addressInfo['district_name'];
        $requestGet['detail_address'] = $addressInfo['detail_address'];
        $requestGet['national_code'] = $addressInfo['national_code'];

        $Order = new Order;
        return $Order->updateMemOrder($requestGet, 1);
    }

    // 选择发货方式 事件
    public function chooseExpressType(Request $request)
    {
        $orderId = $request['id'];
        $nationalCode = $request['national_code'];
        $expressType = $request['express_type'];

        $requestGet = [];
        $requestGet['id'] = $orderId;
        $requestGet['express_type'] = $expressType;
        $requestGet['national_code'] = $nationalCode;

        $Order = new Order;
        return $Order->updateMemOrder($requestGet, 2);
    }

    // 计算邮费 => 涉及邮费model
    public function getExp(Request $request)
    {
        // 邮寄类型 / 国家码 / 订单ID
        $expressType = 'ZTO';
        $nationalCode = 110000;
        $orderId = 1;

        $Order = new Order;
        $orederInfo = $Order->getOrder($orderId);
        if (empty($orederInfo)) {
            return $this->errorClient('', '订单不存在');
        }
        $weightArr = json_decode($orederInfo['express_weight'], 1);
        $storeId = $orederInfo['store_id'];
        $getExp = $Order->getExp($expressType, $nationalCode, $weightArr, $storeId);
        return $getExp;
    }

    // 会员订单支付验证 并 支付
    public function checkMemPay(Request $request)
    {
        $type = $request['payType'];// 支付类型 1 余额支付 / 2 微信支付
        $orderId = $request['id'];
        $passwordPay = isset($request['password_pay']) ? $request['password_pay'] : 0;
        // $type = 1;// 支付类型 1 余额支付 / 2 微信支付
        // $orderId = 1;
        // $passwordPay = 123456;
        $Order = new Order;
        $orderCheck = $Order->checkMemPay($type, $orderId, $passwordPay);
        return $orderCheck;
    }

    public function getList(Request $request)
    {
        $order = new Order;
        $data = $order->getList($request);

        return $data;
    }
}
